<template>
  <public-dialog
    v-model:visible="visible"
    title="预算调整"
    confirm-button-title="确认"
    width="80%"
    @onConfirm="onConfirm"
  >
    <div class="m-b10">
        <el-button size="small" @click="onAdd">
            <svg-icon icon-class="add-icon-1" class="m-r5"></svg-icon>
            新增</el-button>
        <el-button size="small" type="danger" @click="onDelete">
            <svg-icon icon-class="delete-icon" class="m-r5"></svg-icon>
            删除</el-button>
    </div>
      <el-form label-width="0px" ref="tableFormRef" :model="form">
          <el-table
                  :header-cell-style="{ background: '#f7f7fa' }"
                  ref="tableRef"
                  :data="form.list"
                  @selection-change="handleSelectionChange"
          >
              <el-table-column class="table-column" type="selection" :selectable="selectable"></el-table-column>
              <el-table-column
                      type="index"
                      label="序号"
                      align="center"
                      min-width="50"
              >
                  <template #default="scope">
                      <el-form-item>
                          <span>{{ scope.$index + 1 }}</span>
                      </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="类型" prop="type">
                  <template #default="scope">
                      <el-form-item>
                          <span>{{ scope.row.type }}</span>
                      </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="所属主项目" prop="mainProjectId" min-width="100">
                  <template #default="scope">
                      <el-form-item
                          :prop="'list.' + scope.$index + '.mainProjectId'"
                          :rules="rules.mainProjectId"
                      >
                          <el-select
                              :disabled="scope.row.disabled"
                              filterable
                              v-model="scope.row.mainProjectId"
                              @change="mainProjectIdChange($event, scope.$index)"
                              clearable
                          >
                              <el-option
                                  v-for="(item, index) in projectSetList"
                                  :key="index"
                                  :label="item.projectSetName"
                                  :value="item.projectSetId"
                              ></el-option>
                          </el-select>
                      </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="相关项目" prop="subprojectId" min-width="100">
                  <template #default="scope">
                      <el-form-item
                          :prop="'list.' + scope.$index + '.subprojectId'"
                          :rules="rules.subprojectId"
                      >
                          <el-select
                              :disabled="scope.row.disabled"
                              filterable
                              v-model="scope.row.subprojectId"
                              clearable
                              @change="projectChange($event, scope.$index)"
                          >
                              <el-option
                                  v-for="(item, index) in form.list[scope.$index]
											.projectList"
                                  :key="index"
                                  :label="item.projectName"
                                  :value="item.projectId"
                              ></el-option>
                          </el-select>
                      </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="年度" prop="year">
                  <template #default="scope">
                      <el-form-item>
                          <span>{{ scope.row.year || '-' }}</span>
                      </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="季度" prop="quarter">
                  <template #default="scope">
                      <el-form-item>
                          <span>{{ scope.row.quarter || '-' }}</span>
                      </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="月度" prop="monthly">
                  <template #default="scope">
                      <el-form-item>
                          <span>{{ scope.row.monthly || '-' }}</span>
                      </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="相关合同" prop="contractId" min-width="100">
                  <template #default="scope">
                      <el-form-item
                              :prop="'list.' + scope.$index + '.contractId'"
                              :rules="rules.contractId"
                      >
                          <el-select :disabled="scope.row.disabled" filterable v-model="scope.row.contractId" clearable>
                              <el-option
                                      v-for="(item, index) in form.list[scope.$index]
											.contractList"
                                      :key="index"
                                      :label="item.contractName"
                                      :value="item.contractId"
                              ></el-option>
                          </el-select>
                      </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="资金预算科目" prop="subjectId" min-width="100" show-overflow-tooltip>
                  <template #default="scope">
                      <span class="m-b20">{{scope.row.subjectName}}</span>
                        <!--                      <el-form-item
                              :prop="'list.' + scope.$index + '.subjectId'"
                              :rules="rules.subjectId"
                      >
                          <span v-if="scope.row.disabled">{{scope.row.subjectName}}</span>
                          <el-cascader
                                  v-else
                                  clearable
                                  placeholder="请选择"
                                  v-model="scope.row.subjectId"
                                  :props="props"
                                  :options="scope.row.options"
                          />
                      </el-form-item>-->
                  </template>
              </el-table-column>
              <el-table-column label="原预算金额" prop="budgetAmount">
                  <template #default="scope">
                      <el-form-item>
                          <span>{{ scope.row.budgetAmount || '-' }}</span>
                      </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="可调整金额" prop="adjustAmount">
                  <template #default="scope">
                      <el-form-item
                              :prop="'list.' + scope.$index + '.adjustAmount'"
                              :rules="rules.adjustAmount"
                      >
                          <span v-if="scope.$index===0">{{ scope.row.adjustAmount || '0' }}</span>
                          <el-input
                                  v-else
                                  v-model="scope.row.adjustAmount"
                                  @input="(e)=>{
                                      inputEvent(scope.$index,e);
                                      scope.row.adjustAmount = limitInputNum(scope.row.adjustAmount,13,3,true)}"
                                  placeholder="请输入调整后金额"
                          />
                      </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="备注" min-width="100">
                  <template #default="scope">
                      <el-form-item :prop="'list.' + scope.$index + '.remarks'">
                          <el-input
                                  clearable
                                  v-model="scope.row.remarks"
                                  placeholder="请输入备注"
                          />
                      </el-form-item>
                  </template>
              </el-table-column>
          </el-table>
      </el-form>


  </public-dialog>
</template>

<script setup>
import PublicDialog from "@/components/PublicDialog.vue";
import {reactive, ref} from "vue";
import SvgIcon from "@/components/SvgIcon/index.vue";
import {budgetManagement, fundManagementApi, otherApi} from "@/api/businessFinance";
import {ElCascader, ElForm, ElFormItem, ElMessage, ElOption, ElSelect, ElTable, ElTableColumn} from "element-plus";
import {limitInputNum} from "@/common/utils/GlobalUtils";

const visible = ref(false);
const selectList = ref([]);
const adjustAmount = ref(0);
const totalAdjustAmount = ref(0);
const oldAdjustAmount2 = ref(0);

let form = reactive({
    departmentId: "",
    year: "",
    quarter: "",
    mainProjectId: "",
    moneyType: "",
    planType: "",
    temp: "",
    list: [],
    businessUnitId: "",
});

const validateAdjustAmount = (rule, value, callback) => {
    if (value === '' || value===0) {
        callback(new Error('金额必须大于零!'));
    } else {
        callback()
    }
}

const rules = reactive({
    departmentId: [
        { required: true, message: "编制部门不能为空!", trigger: "change" },
    ],
    year: [{ required: true, message: "年度不能为空!", trigger: "blur" }],
    quarter: [{ required: true, message: "季度不能为空!", trigger: "change" }],
    mainProjectId: [
        { required: true, message: "主项目不能为空!", trigger: "change" },
    ],
    temp: [
        { required: true, message: "资金预算性质不能为空!", trigger: "change" },
    ],
    monthly: [{ required: true, message: "月度不能为空!", trigger: "change" }],
    subprojectId: [
        { required: true, message: "相关项目不能为空!", trigger: "change" },
    ],
    contractId: [
        { required: true, message: "相关合同不能为空!", trigger: "change" },
    ],
    subjectId: [
        { required: true, message: "资金预算科目不能为空!", trigger: "change" },
    ],
    adjustAmount: [
        { required: true, message: "金额不能为空!", trigger: "blur" },
        { validator: validateAdjustAmount, trigger: 'blur' }
    ],
    planType: [
        { required: true, message: "计划类型不能为空!", trigger: "change" },
    ],
    businessUnitId: [
        { required: true, message: "业务单元不能为空!", trigger: "change" },
    ],
});

const page = reactive({
    total: 0,
    current: 1,
    size: 10
});

const tableData = ref([]);


/**
 * 分页
 * @param e
 */
const onPageChange = (e) => {
    page.current = e.page;
    page.size = e.limit;
    let param = {
        param: {
            queryName: "",
        },
        pageNum: page.current,
        pageSize: page.size,
    }
}

/**
 * 多选
 * @param e
 */
const handleSelectionChange = (e) => {
    selectList.value = e;
}

const getUuid = () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0,
            v = c == 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
    });
}

/**
 * 新增
 */
const onAdd = () => { // 原预算金额  // 调整后金额
  let params = {
      ...JSON.parse(JSON.stringify(form.list[0])),
      id:getUuid()
  };
  params.type = '新增';
  params.budgetAmount = 0;
  params.adjustAmount = 0;
  params.remarks = '';
  params.disabled = false;
  // params.subjectId = '';
  params.mainProjectId = '';
  params.subprojectId = '';
  params.contractId = '';
  params.budgetPlanId = '';
  form.list.push(params);
}


const projectSetList = ref([]);
/**
 * 项目集
 */
const getProjectSets = () => {
    fundManagementApi.getProjectSets().then((res) => {
        projectSetList.value = res.data;
    });
};

/**
 * 项目
 * @param projectSetId
 * @param i
 */
const getProjects = (projectSetId,i) => {
    fundManagementApi.getProjects(projectSetId).then((res) => {
        form.list[i].projectList = res.data;
    });
};

/**
 * 所属主项目id选中时触发
 * @param e
 * @param i
 */
const mainProjectIdChange = (e, i) => {
    if (e) {
        getProjects(e, i);
        form.list[i].projectList = [];
        form.list[i].contractList = [];
        form.list[i].contractId = "";
        form.list[i].subprojectId = "";
    } else {
        form.list[i].projectList = [];
        form.list[i].contractList = [];
        form.list[i].contractId = "";
        form.list[i].subprojectId = "";
    }
};

const getListByProjectId = (projectId, i) => {
    otherApi.getContractList(projectId).then((res) => {
        form.list[i].contractList = res.data;
    });
};

/**
 * 项目选择器下拉选择时触发
 *
 */
const projectChange = (e, i) => {
    if (e) {
        form.list[i].contractId = "";
        getListByProjectId(e, i);
    } else {
        form.list[i].contractList = [];
        form.list[i].contractId = "";
    }
};

const props = {
    lazy: true,
    async lazyLoad(node, resolve) {
        const { level } = node;
        try {
            if (level === 0) {
                const res = await fundManagementApi.getBudgetSubjectList({
                    subjectId:"",
                    subjectType: "1",
                });
                let nodes = [];
                res.data.forEach((item) => {
                    nodes.push({
                        value: item.subjectId,
                        label: item.subjectName,
                        leaf: level >= 4,
                    });
                });
                resolve(nodes);
            }
            if (level > 0 && level === 5) {
                resolve([]);
            }
            if (level > 0 && level < 5) {
                const res = await fundManagementApi.getBudgetSubjectList({
                    subjectId: node.value,
                    subjectType: "1",
                });
                let nodes = [];
                res.data.forEach((item) => {
                    nodes.push({
                        value: item.subjectId,
                        label: item.subjectName,
                        leaf: level >= 4,
                    });
                });
                resolve(nodes);
            }
        }catch (e) {
            let nodes = [];
            resolve(nodes);
        }

    },
};

/**
 * 打开弹窗
 */
const openPopup = (row) => {
  oldAdjustAmount2.value =  row.adjustAmount;
  totalAdjustAmount.value = row.budgetAmount - row.adjustAmount; // 可拆分金额
  row.adjustAmount =  totalAdjustAmount.value;
  form.list = [{...row,type:'原单',disabled:true,id:getUuid(),projectSetList:[],contractList:[]}];
  visible.value = true;
  getProjectSets();
  getProjects(row.mainProjectId,0);
  getListByProjectId(row.subprojectId,0);
}

const selectable = (row, index) => {
    if (row.disabled) {
        return false;
    } else {
        return true;
    }
};

const tableFormRef = ref(null);
const emits = defineEmits(['onSuccess']);

/**
 * 确认
 */
const onConfirm = () => {
    tableFormRef.value.validate((valid, fields) => {
        if (valid) {
            if(form.list[0].adjustAmount <= 0){
                return ElMessage.error('原单金额不能小于已执行金额!');
            }
            let total = 0;
            form.list.forEach(item=>{
                total+= parseFloat(item.adjustAmount);
            });
            if(totalAdjustAmount.value !== total){
                return ElMessage.error('原单金额必须等于调整后金额!');
            }
            let params = {
                departmentName: form.list[0].departmentName,
                departmentId: form.list[0].departmentId,
                year: form.list[0].year,
                quarter: form.list[0].quarter,
                planType: form.list[0].planType,
                list:form.list
            };
            params.list[0].adjustAmount = oldAdjustAmount2.value +  params.list[0].adjustAmount;
            params.list.forEach((item,index)=>{
               if(Array.isArray(item.subjectId)){
                   item.subjectId = item.subjectId[item.subjectId.length-1]
               }
            });

            budgetManagement.budgetSplitting(params).then(res=>{
                if(res.code==='200'){
                    visible.value = false;
                    ElMessage.success('操作成功!');
                    emits('onSuccess');
                }else{
                    visible.value = false;
                    ElMessage.error(res.msg);
                }
            });

        } else {
            console.log('error submit!', fields)
        }
    })
}

/**
 * 获取参数
 */
const getValue = () => {
    let oldAdjustAmount = 0;
    for(let item of form.list.slice(1)){
        oldAdjustAmount = oldAdjustAmount + parseFloat(item.adjustAmount || 0);
    }
    return {oldBudgetAmount:totalAdjustAmount.value,oldAdjustAmount:oldAdjustAmount}
}

/**
 * 输入事件
 */
const inputEvent = (i,e) => {
    let {oldBudgetAmount,oldAdjustAmount} = getValue();
    if((oldBudgetAmount -  oldAdjustAmount)<=0){
        form.list[i].adjustAmount = 0;
        oldBudgetAmount =  getValue().oldBudgetAmount;
        oldAdjustAmount =  getValue().oldAdjustAmount;
    }
    form.list[0].adjustAmount = (oldBudgetAmount -  oldAdjustAmount);
}

/**
 * 删除
 */
const onDelete = () => {
    for(let i = 0;i<form.list.length;i++){
        for (let j = 0;j<selectList.value.length;j++){
            if(form.list[i].id === selectList.value[j].id){
                form.list.splice(i,1);
            }
        }
    }

    let {oldBudgetAmount,oldAdjustAmount} = getValue();
    form.list[0].adjustAmount = (oldBudgetAmount -  oldAdjustAmount);
}

defineExpose({openPopup});
</script>

<style lang="scss" scoped>
:deep(.table-column){
    .el-checkbox{
        margin-bottom: 100px !important;
    }
}
</style>
